import toast from '../../utils/toast';

let timer = null;
let count = 0;

function setTimer(callback, duration = 0) {
  clearTimer();
  if (duration > 0) {
    timer = setTimeout(callback, duration);
  } else {
    callback();
  }
}

function clearTimer() {
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }
}

/**
 * @description: 显示loading
 * @param {String} message
 * @param {Number} loadingTime
 * @return {void}
 */
function show(message, loadingTime) {
  count++;
  setTimer(() => {
    toast.loading({
      message,
      custom: 'requestLoading',
    });
  }, loadingTime);
}

/**
 * @description: 关闭loading
 * @param {Number} loadingHideDelayTime
 * @return {void}
 */
function hide(loadingHideDelayTime = 0) {
  clearTimer();
  if (count > 0 && --count <= 0) {
    setTimer(() => {
      if (count <= 0) {
        toast.state.custom === 'requestLoading' && toast.hide();
      }
    }, loadingHideDelayTime);
  }
}

const loading = {
  show,
  hide,
};

export default loading;
